package graph

import (
	"bufio"
	"fmt"
	"log"
	"os"
	"strconv"
	"strings"
)

type CLGraph struct {
	list []*VexNode
	kind int
	arcnum, vexnum int
}

type ArcNode struct {
	tailvex, headvex int
	tlink, hlink *ArcNode
	weight int
}

type VexNode struct {
	firstin, firstout *ArcNode
	data int
}

func (cg *CLGraph)locateVex(value int) int {
	for k,v := range cg.list {
		if value == v.data {
			return k
		}
	}
	return -1
}

func CreateCLGraph() *CLGraph {
	reader := bufio.NewReader(os.Stdin)
	str, err := reader.ReadString('\n')
	if err != nil{
		log.Fatalln("error", err)
	}
	strs := strings.Split(str[:len(str)-1], " ")
	vertexes := make([]*VexNode, len(strs))
	for k,v := range strs {
		number, _ := strconv.Atoi(v)
		vertexes[k] = &VexNode{
			data: number,
		}
	}
	newcg := &CLGraph{
		list: vertexes,
	}
	for {
		var headV, tailV, weight int
		_, err := fmt.Scanf("%d->%d %d", &tailV, &headV, &weight)
		if err != nil{
			break
		}
		headK := newcg.locateVex(headV)
		tailK := newcg.locateVex(tailV)
		newNode := &ArcNode{
			tailvex: tailK,
			headvex: headK,
			tlink:   newcg.list[tailK].firstout,
			hlink:   newcg.list[headK].firstin,
			weight:  weight,
		}
		newcg.list[tailK].firstout = newNode
		newcg.list[headK].firstin = newNode
	}
	return newcg
}

func (cg *CLGraph) PrintAll(){
	for k,v := range cg.list {
		fmt.Printf("%d ~ tailList: ", k)
		for temp := v.firstout; temp != nil; temp = temp.tlink {
			fmt.Print(*temp, " ")
		}
		fmt.Println()
	}

	for k,v := range cg.list {
		fmt.Printf("%d ~ headList: ", k)
		for temp := v.firstin; temp != nil; temp = temp.hlink {
			fmt.Print(*temp, " ")
		}
		fmt.Println()
	}
}
